// 簿记行为交收页面
import React from 'react';
import { connect } from 'dva';
import { PrimaryC, PrimaryGhostC, TableC } from '../../../comps';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Modal } from 'antd';
import DetailC from './behaviorDetail';
import _ from 'lodash';
const confirm = Modal.confirm;
@Form.create()
class BehaviorQueryC extends React.Component {
  // props默认值
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
  };
  state = {
    currentPage: 1, // 当前页码
    pageSize: 10, // 一页数量
    isReset: false, // 标记是否点击了“重置”后未重新查询
    queryItems: {
      // 存储最新的查询条件
      search_GTE_createdTs: moment().subtract(1, 'months'),
      search_LTE_createdTs: moment(),
    },
    columns: [], //列表列
    dataSource: [], //列表内容
    visible: false, //详情模态框
    visible1: false, //交收模态框
    detailObj: {}, //传入模态框内容
    selectedRowKeys: [],
    selectedRows: [],
    isInstruction: false,
    isgoBack: false,
  };
  componentDidMount() {
    this.props.onRef(this);
    const query = {
      search_GTE_createdTs: moment().subtract(1, 'months').format('YYYY-MM-DD'),
      search_IN_method: '0;1',
      search_LTE_createdTs: moment().format('YYYY-MM-DD'),
      userId: localStorage.getItem('antd-pro-userId'),
    };
    this.onQuery(query);
  }
  //获取列表内容
  getList = () => {
    const { queryItems, currentPage, pageSize } = this.state;
    const { columns } = this.props.bookkeepingBehaviorM;
    this.props.dispatch({
      type: 'bookkeepingBehaviorM/getBehavioeList',
      payload: {
        ...queryItems,
        current: currentPage,
        pageSize: pageSize,
      },
      callback: (data) => {
        if (data && data.dataSource) {
          let columnss = _.cloneDeep(columns);
          this.changeColumns(columnss);
          this.setState({
            dataSource: data.dataSource,
            total: data.pageInfo.total,
            currentPage: data.pageInfo.currentPage,
            pageSize: data.pageInfo.pageSize,
            selectedRowKeys: [],
            selectedRows: [],
            isgoBack: false,
            isInstruction: false,
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            selectedRowKeys: [],
            selectedRows: [],
            isgoBack: false,
            isInstruction: false,
          });
        }
      },
    });
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.state.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this,
        this.setState({
          isReset: false,
        });
      return;
    }
    this.setState(
      {
        currentPage: current,
        pageSize: pageSize,
      },
      () => {
        this.getList();
      },
    );
  };
  //添加操作列
  changeColumns = (columns) => {
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 100,
        operates: [
          {
            title: '详情',
            onClick: (record, index) => {
              this.detailAccount(record);
            },
          },
          {
            //交收状态时已交收和到期交收时不可点击
            title: '交收',
            onClick: (record, index) => {
              this.settleAccount(record);
            },
            rules: {
              disabled: {
                items: [
                  { key: 'instructionStatus', value: ['7', '8', '4'], relation: ['=', '=', '='] },
                  { key: 'bondOffStatus', value: ['0'], relation: ['='] },
                ],
                relation: 'or',
              },
            },
          },
        ],
      });
    }
    this.setState({ columns: columns });
  };

  //详情点击
  detailAccount = (record) => {
    this.setState({
      visible: true,
      detailObj: record,
    });
  };

  //交收点击
  settleAccount = (record) => {
    this.setState({
      visible1: true,
      detailObj: record,
    });
  };

  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
      visible1: msg,
    });
  };

  // 响应查询
  onQuery = (query) => {
    let queryItems = {
      params: query,
    };
    this.setState({ queryItems: queryItems, isReset: false, currentPage: 1 }, () => this.getList());
  };

  // 响应重置
  onClear = () => {
    this.setState({ isReset: true, currentPage: 1, pageSize: 10 });
  };

  // 回溯
  goBack = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    let keys = selectedRows.map((item) => (item.instructionStatus == '4' || item.instructionStatus == '7' || item.instructionStatus == '8') && item.id).filter((item) => item);
    let ids = keys.join(';');
    const that = this;
    confirm({
      title: '只针对已交收的交易进行回溯，确定回溯?',
      cancelText: '取消',
      okText: '确定',
      onOk() {
        dispatch({
          type: 'bookkeepingBehaviorM/getBehaviorInstructionHS',
          payload: {
            ids,
          },
          callback: (res) => {
            if (res === 'success') {
              that.setState({
                selectedRowKeys: [],
                selectedRows: [],
                isgoBack: false,
                isInstruction: false,
              });
              that.refresh();
            }
          },
        });
        return new Promise((resolve, reject) => {
          setTimeout(resolve, 100);
        });
      },
    });
  };

  //批量交收
  orderInstruction = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    let keys = selectedRows.map((item) => (item.instructionStatus == '6' || item.instructionStatus == '11') && item.id).filter((item) => item);
    let ids = keys.join(';');
    const that = this;
    confirm({
      title: '只针对未交收的交易进行交收，确定交收?',
      cancelText: '取消',
      okText: '确定',
      onOk() {
        dispatch({
          type: 'bookkeepingBehaviorM/getBatchInstruction',
          payload: {
            ids,
          },
          callback: (res) => {
            if (res === 'success') {
              that.setState({
                selectedRowKeys: [],
                selectedRows: [],
                isgoBack: false,
                isInstruction: false,
              });
              that.refresh();
            }
          },
        });
        return new Promise((resolve, reject) => {
          setTimeout(resolve, 100);
        });
      },
    });
  };

  //列表点击响应
  onSelectChange = (selectedRowKeys, selectedRows) => {
    let isgoBack = selectedRows.some((item) => item.instructionStatus == '4' || item.instructionStatus == '7' || item.instructionStatus == '8');
    let isInstruction = selectedRows.some((item) => item.instructionStatus == '6' || item.instructionStatus == '11');

    this.setState({
      selectedRowKeys,
      selectedRows,
      isgoBack,
      isInstruction,
    });
  };

  // 刷新
  refresh = () => {
    let { isReset } = this.state;
    if (isReset) {
      message.warning('查询条件已重置，请重新查询！');
    } else {
      this.getList();
    }
  };

  render() {
    let { columns, dataSource, total, currentPage, pageSize, visible, selectedRowKeys, visible1, isInstruction, isgoBack } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <PrimaryC
          title='回溯'
          onClick={this.goBack}
          loading={this.props.loading.effects['bookkeepingBehaviorM/getBehaviorInstructionHS'] === true}
          disabled={!isgoBack}
          style={{ marginRight: '10px' }}
        />
        <PrimaryC
          title='批量交收'
          onClick={this.orderInstruction}
          loading={this.props.loading.effects['bookkeepingBehaviorM/getBatchInstruction'] === true}
          disabled={!isInstruction}
        />
        <div style={{ float: 'right' }}>
          <PrimaryGhostC title='刷新' onClick={this.refresh} style={{ marginRight: '10px' }} />
        </div>
        <div style={{ marginTop: '16px' }}>
          <TableC
            rowSelection={rowSelection}
            columns={columns}
            loading={this.props.loading.effects['bookkeepingBehaviorM/getBehavioeList']}
            dataSource={dataSource}
            current={currentPage}
            pageSize={pageSize}
            total={total}
            scroll={{ x: 'max-content' }}
            selfScrollY={true}
            rowKey='id'
            pagination={true}
            onChange={this.handleTableChange}
          />
        </div>

        {(visible || visible1) && (
          <DetailC visible={this.state.visible} visible1={this.state.visible1} detailObj={this.state.detailObj} changeVisible={this.changeVisible} refresh={this.refresh} />
        )}
      </div>
    );
  }
}

export default connect(({ bookkeepingBehaviorM, loading }) => ({ bookkeepingBehaviorM, loading }))(BehaviorQueryC);
